# import matplotlib.pyplot as plt  # 导入pyplot模块
# plt.rcParams['font.sans-serif'] = ['SimHei']
# # 解决中文乱码问题
# plt.rcParams['axes.unicode_minus'] = False  # 解决正负号乱码问题
# months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']  # 准备月份信息
# max_temps = [2, 6, 14, 21, 28, 31, 32, 31, 26, 19, 10, 4]  # 准备平均最高温度数据
# min_temps = [-7, -5, 2, 9, 16, 20, 24, 22, 17, 9, 1, -5]  # 准备平均最低温度数据
# precipitation = [3.2, 5.1, 0.0, 0.5, 8.7, 15.4, 12.3, 2.1, 0.0, 1.2, 6.8, 20.1, 7.5, 3.0, 0.2]
# plt.ﬁgure(ﬁgsize=(16, 4), dpi=150)  # 定义画布尺寸和分辨率
# plt.grid(linestyle=":", alpha=0.5)  # 添加画布网格
# for i,txt in enumerate(max_temps):
#     plt.annotate(f'{txt}℃', (months[i], max_temps[i]), textcoords="offset points", xytext=(0, -15), ha='center', color='red')
# for i,txt in enumerate(min_temps):
#     plt.annotate(f'{txt}℃', (months[i], max_temps[i]), textcoords="offset points", xytext=(0, -40), ha='center', color='blue')
# plt.xlabel("月份")  # 添加x轴标签
# plt.ylabel("温度（单位：℃）")  # 添加y轴标签
# plt.title("北京市全年逐月平均最高/最低温度")  # 添加图表标题
# plt.plot(months, max_temps, color="r", label="平均最高温度")  # 绘制平均最高温度折线图
# plt.plot(months, min_temps, color="b", label="平均最低温度")  # 绘制平均最低温度折线图
# plt.legend()  # 绘制图例，需要先在绘制曲线的同时，添加曲线的label标签
# plt.savefig('temp.png')
# plt.show()
# import matplotlib.pyplot as plt
# import numpy as np
#
# # 设置中文字体
# plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
# plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题
#
# # 未来15天的索引
# days = np.arange(1, 16)
#
# # 最低温数据
# min_temps = [22, 23, 24, 25, 24, 25, 24, 23, 22, 23, 24, 25, 24, 23, 22]
# # 最高温数据
# max_temps = [29, 30, 31, 32, 33, 34, 31, 30, 29, 30, 32, 33, 31, 30, 29]
# # 降水量数据
# precipitation = [3.2, 5.1, 0.0, 0.5, 8.7, 15.4, 12.3, 2.1, 0.0, 1.2, 6.8, 20.1, 7.5, 3.0, 0.2]
#
# # 创建一个包含两个y轴的子图
# fig, ax1 = plt.subplots()
#
# # 绘制最低温和最高温折线图
# line_min, = ax1.plot(days, min_temps, 'o-', label='最低温(°C)', color='blue')
# line_max, = ax1.plot(days, max_temps, 'o-', label='最高温(°C)', color='red')
# ax1.set_xlabel('天数')
# ax1.set_ylabel('温度(°C)', color='black')
# ax1.tick_params(axis='y', labelcolor='black')
#
# # 为温度折线图添加数据标签
# for i, (day, min_temp, max_temp) in enumerate(zip(days, min_temps, max_temps)):
#     ax1.annotate(f'{min_temp}°',
#                 (day, min_temp),
#                 textcoords="offset points",
#                 xytext=(0,20),  # 增大垂直偏移量，避免被遮挡
#                 ha='center',
#                 color='blue')
#     ax1.annotate(f'{max_temp}°',
#                 (day, max_temp),
#                 textcoords="offset points",
#                 xytext=(0,20),  # 增大垂直偏移量，避免被遮挡
#                 ha='center',
#                 color='red')
#
# # 创建第二个y轴
# ax2 = ax1.twinx()
# # 绘制降水量柱状图，设置透明度为0.7
# ax2.bar(days, precipitation, width = 0.4, label='降水量(mm)', color='green', alpha=0.7)
# ax2.set_ylabel('降水量(mm)', color='green')
# ax2.tick_params(axis='y', labelcolor='green')
#
# # 设置x轴刻度标签为天数
# plt.xticks(days)
#
# # 添加图例
# lines, labels = ax1.get_legend_handles_labels()
# lines2, labels2 = ax2.get_legend_handles_labels()
# ax2.legend(lines + lines2, labels + labels2, loc='upper right')
#
# # 设置图表标题
# plt.title('清远市未来15天的天气图')
#
# # 显示图表
# plt.show()
# import matplotlib.pyplot as plt
# import numpy as np
#
# # 设置中文字体
# plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
# plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题
#
# # 未来15天的索引
# days = np.arange(1, 16)
#
# # 最低温数据
# min_temps = [22, 23, 24, 25, 24, 25, 24, 23, 22, 23, 24, 25, 24, 23, 22]
# # 最高温数据
# max_temps = [29, 30, 31, 32, 33, 34, 31, 30, 29, 30, 32, 33, 31, 30, 29]
#
# # 创建图表
# fig, ax = plt.subplots()
#
# # 绘制最低温和最高温折线图
# line_min, = ax.plot(days, min_temps, 'o-', label='最低温(°C)', color='blue')
# line_max, = ax.plot(days, max_temps, 'o-', label='最高温(°C)', color='red')
#
# # 为温度折线图添加数据标签
# for i, (day, min_temp, max_temp) in enumerate(zip(days, min_temps, max_temps)):
#     ax.annotate(f'{min_temp}°',
#                 (day, min_temp),
#                 textcoords="offset points",
#                 xytext=(0,10),  # 调整标签位置
#                 ha='center',
#                 color='blue')
#     ax.annotate(f'{max_temp}°',
#                 (day, max_temp),
#                 textcoords="offset points",
#                 xytext=(0,10),  # 调整标签位置
#                 ha='center',
#                 color='red')
#
# # 设置坐标轴标签
# ax.set_xlabel('天数')
# ax.set_ylabel('温度(°C)')
#
# # 设置x轴刻度标签为天数
# plt.xticks(days)
#
# # 添加图例
# ax.legend(loc='upper left')
#
# # 设置图表标题
# plt.title('清远市未来15天的天气图')
#
# # 添加网格线
# plt.grid(True, linestyle='--', alpha=0.7)
#
# # 调整布局
# plt.tight_layout()
#
# # 显示图表
# plt.show()
# import matplotlib.pyplot as plt
# import numpy as np
# import matplotlib.dates as mdates
# from datetime import datetime, timedelta
# import random
#
# # 设置中文字体
# plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
# plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题
#
# # 创建一个包含两个子图的图表
# fig = plt.figure(figsize=(16, 8))  # 调整图表大小以容纳两个子图
#
# # 左侧子图：天气数据（占2/3宽度）
# ax1 = fig.add_axes([0.05, 0.1, 0.6, 0.8])  # [left, bottom, width, height]
#
# # 生成未来15天的日期
# start_date = datetime.now()
# dates = [start_date + timedelta(days=i) for i in range(15)]
# date_labels = [date.strftime('%m-%d') for date in dates]
#
# # 生成模拟的天气数据
# np.random.seed(42)  # 设置随机种子，确保结果可重现
# min_temps = np.random.randint(15, 25, 15)  # 最低温度在15-25度之间
# max_temps = min_temps + np.random.randint(5, 10, 15)  # 最高温度比最低温度高5-10度
# precipitation = np.random.exponential(10, 15)  # 降水量，使用指数分布模拟
# precipitation = np.clip(precipitation, 0, 50)  # 限制降水量在0-50mm之间
#
# # 绘制最高温和最低温折线图
# ax1.plot(date_labels, max_temps, 'o-', color='#FF5722', label='最高温度 (°C)', linewidth=2)
# ax1.plot(date_labels, min_temps, 'o-', color='#2196F3', label='最低温度 (°C)', linewidth=2)
#
# # 添加温度数据标签
# for i, (date, max_temp, min_temp) in enumerate(zip(date_labels, max_temps, min_temps)):
#     ax1.annotate(f'{max_temp}°', (date, max_temp), textcoords='offset points',
#                  xytext=(0,15), ha='center', color='#FF5722', fontweight='bold')
#     ax1.annotate(f'{min_temp}°', (date, min_temp), textcoords='offset points',
#                  xytext=(0,-20), ha='center', color='#2196F3', fontweight='bold')
#
# # 设置左侧Y轴（温度）
# ax1.set_ylabel('温度 (°C)', fontsize=12)
# ax1.set_ylim(min(min_temps) - 5, max(max_temps) + 5)
# ax1.tick_params(axis='y', labelcolor='black')
#
# # 创建第二个Y轴用于降水量
# ax2 = ax1.twinx()
#
# # 绘制降水量柱状图
# bars = ax2.bar(date_labels, precipitation, width=0.6, color='#4CAF50', alpha=0.6, label='降水量 (mm)')
#
# # 为降水量超过5mm的日期添加数据标签
# for bar in bars:
#     height = bar.get_height()
#     if height > 5:  # 只显示降水量大于5mm的标签，避免图表过于拥挤
#         ax2.annotate(f'{height:.1f}mm',
#                     xy=(bar.get_x() + bar.get_width() / 2, height),
#                     xytext=(0, 3),  # 3 points vertical offset
#                     textcoords="offset points",
#                     ha='center', va='bottom',
#                     fontsize=9)
#
# # 设置右侧Y轴（降水量）
# ax2.set_ylabel('降水量 (mm)', fontsize=12)
# ax2.set_ylim(0, max(precipitation) * 1.2)  # 稍微扩展Y轴上限，使图表更美观
# ax2.tick_params(axis='y', labelcolor='black')
#
# # 设置X轴
# plt.xticks(rotation=45, ha='right')
# ax1.set_xlabel('日期', fontsize=12)
#
# # 添加标题和图例
# ax1.set_title('清远市未来15天天气预报', fontsize=16, fontweight='bold')
# lines, labels = ax1.get_legend_handles_labels()
# lines2, labels2 = ax2.get_legend_handles_labels()
# ax1.legend(lines + lines2, labels + labels2, loc='upper right')
#
# # 添加网格线
# ax1.grid(True, linestyle='--', alpha=0.7)
#
# # 右侧子图：2025年国内热门游戏排行饼状图（占1/3宽度）
# ax3 = fig.add_axes([0.7, 0.15, 0.25, 0.7])  # [left, bottom, width, height]
#
# # 使用用户指定的游戏数据
# games = ['王者荣耀', '原神', '和平精英', '金铲铲之战', '第五人格', '开心消消乐', '贪吃蛇大作战', '其他']
# shares = [35, 20, 12, 10, 8, 6, 5, 4]
# colors = ['#FF9800', '#2196F3', '#4CAF50', '#9C27B0', '#F44336', '#FFC107', '#03A9F4', '#607D8B']
# explode = (0.1, 0, 0, 0, 0, 0, 0, 0)  # 突出显示第一个游戏
#
# # 绘制饼图
# patches, texts, autotexts = ax3.pie(shares, explode=explode, labels=games, colors=colors,
#                                      autopct='%1.1f%%', startangle=90, pctdistance=0.85)
#
# # 设置饼图为圆形
# ax3.axis('equal')
#
# # 设置饼图标题
# ax3.set_title('2025年国内热门游戏市场份额', fontsize=14, fontweight='bold')
#
# # 调整图例位置
# plt.tight_layout()
#
# # 显示图表
# plt.show()
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import random

# 设置中文字体
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题

# 创建一个包含三个子图的图表
fig = plt.figure(figsize=(18, 12))  # 调整图表大小以容纳三个子图

# 左上角子图：天气数据（占1/2宽度和2/3高度）
ax1 = fig.add_axes([0.05, 0.35, 0.45, 0.6])  # [left, bottom, width, height]

# 生成未来15天的日期
start_date = datetime.now()
dates = [start_date + timedelta(days=i) for i in range(15)]
date_labels = [date.strftime('%m-%d') for date in dates]

# 生成模拟的天气数据
np.random.seed(42)  # 设置随机种子，确保结果可重现
min_temps = np.random.randint(15, 25, 15)  # 最低温度在15-25度之间
max_temps = min_temps + np.random.randint(5, 10, 15)  # 最高温度比最低温度高5-10度
precipitation = np.random.exponential(10, 15)  # 降水量，使用指数分布模拟
precipitation = np.clip(precipitation, 0, 50)  # 限制降水量在0-50mm之间

# 绘制最高温和最低温折线图
ax1.plot(date_labels, max_temps, 'o-', color='#FF5722', label='最高温度 (°C)', linewidth=2)
ax1.plot(date_labels, min_temps, 'o-', color='#2196F3', label='最低温度 (°C)', linewidth=2)

# 添加温度数据标签
for i, (date, max_temp, min_temp) in enumerate(zip(date_labels, max_temps, min_temps)):
    ax1.annotate(f'{max_temp}°', (date, max_temp), textcoords='offset points',
                 xytext=(0,15), ha='center', color='#FF5722', fontweight='bold')
    ax1.annotate(f'{min_temp}°', (date, min_temp), textcoords='offset points',
                 xytext=(0,-20), ha='center', color='#2196F3', fontweight='bold')

# 设置左侧Y轴（温度）
ax1.set_ylabel('温度 (°C)', fontsize=12)
ax1.set_ylim(min(min_temps) - 5, max(max_temps) + 5)
ax1.tick_params(axis='y', labelcolor='black')

# 创建第二个Y轴用于降水量
ax2 = ax1.twinx()

# 绘制降水量柱状图
bars = ax2.bar(date_labels, precipitation, width=0.6, color='#4CAF50', alpha=0.6, label='降水量 (mm)')

# 为降水量超过5mm的日期添加数据标签
for bar in bars:
    height = bar.get_height()
    if height > 5:  # 只显示降水量大于5mm的标签，避免图表过于拥挤
        ax2.annotate(f'{height:.1f}mm',
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom',
                    fontsize=9)

# 设置右侧Y轴（降水量）
ax2.set_ylabel('降水量 (mm)', fontsize=12)
ax2.set_ylim(0, max(precipitation) * 1.2)  # 稍微扩展Y轴上限，使图表更美观
ax2.tick_params(axis='y', labelcolor='black')

# 设置X轴
plt.xticks(rotation=45, ha='right')
ax1.set_xlabel('日期', fontsize=12)

# 添加标题和图例
ax1.set_title('清远市未来15天天气预报', fontsize=16, fontweight='bold')
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines + lines2, labels + labels2, loc='upper right')

# 添加网格线
ax1.grid(True, linestyle='--', alpha=0.7)

# 右上角子图：2025年国内热门游戏排行饼状图（占1/2宽度和1/3高度）
ax3 = fig.add_axes([0.55, 0.35, 0.4, 0.6])  # [left, bottom, width, height]

# 游戏数据
games = ['王者荣耀', '原神', '和平精英', '金铲铲之战', '第五人格', '开心消消乐', '贪吃蛇大作战', '其他']
shares = [35, 20, 12, 10, 8, 6, 5, 4]
colors = ['#FF9800', '#2196F3', '#4CAF50', '#9C27B0', '#F44336', '#FFC107', '#03A9F4', '#607D8B']
explode = (0.1, 0, 0, 0, 0, 0, 0, 0)  # 突出显示第一个游戏

# 绘制饼图
patches, texts, autotexts = ax3.pie(shares, explode=explode, labels=games, colors=colors,
                                     autopct='%1.1f%%', startangle=90, pctdistance=0.85)

# 设置饼图为圆形
ax3.axis('equal')

# 设置饼图标题
ax3.set_title('2025年国内热门游戏市场份额', fontsize=14, fontweight='bold')

# 底部子图：深圳市福田区二手房面积与售价关系散点图（占整个宽度和1/3高度）
ax4 = fig.add_axes([0.05, 0.05, 0.9, 0.25])  # [left, bottom, width, height]

# 生成模拟的二手房数据（面积和售价）
np.random.seed(10)  # 设置随机种子，确保结果可重现
areas = np.random.normal(90, 30, 50)  # 面积：平均值90平方米，标准差30
prices = areas * 0.12 + np.random.normal(0, 5, 50) + 10  # 售价：线性关系+随机噪声
prices = np.clip(prices, 0, None)  # 确保价格非负

# 添加一些高价值的异常点（豪宅）
luxury_areas = np.random.normal(180, 20, 10)
luxury_prices = luxury_areas * 0.15 + np.random.normal(0, 8, 10) + 30

# 合并普通房屋和豪宅数据
all_areas = np.concatenate([areas, luxury_areas])
all_prices = np.concatenate([prices, luxury_prices])

# 绘制散点图
scatter = ax4.scatter(all_areas, all_prices, c=all_areas, cmap='viridis', alpha=0.7,
                     s=all_prices*5, edgecolor='k', linewidth=1)

# 添加颜色条
cbar = plt.colorbar(scatter, ax=ax4)
cbar.set_label('房屋面积 (平方米)')

# 绘制线性回归线
z = np.polyfit(all_areas, all_prices, 1)
p = np.poly1d(z)
ax4.plot(all_areas, p(all_areas), "r--", linewidth=2)

# 添加标签和标题
ax4.set_xlabel('房屋面积 (平方米)', fontsize=12)
ax4.set_ylabel('售价 (百万元)', fontsize=12)
ax4.set_title('深圳市福田区二手房面积与售价关系', fontsize=14, fontweight='bold')

# 添加网格线
ax4.grid(True, linestyle='--', alpha=0.7)

# 添加趋势注释
ax4.annotate(f'趋势: 售价 = {z[0]:.3f}×面积 + {z[1]:.3f}',
             xy=(0.05, 0.9), xycoords='axes fraction', fontsize=10,
             bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.8))

# 调整布局
plt.tight_layout()

# 显示图表
plt.show()